import { useReactive } from "ahooks";
import { useModel, Outlet } from "umi";
import { Layout, Nav, Button } from "@douyinfe/semi-ui";
import { IconSearch } from "@douyinfe/semi-icons";
import { AutoComplete, Input, Space, Popconfirm, message } from "antd";

import PageLeftMenu from "../components/left.menu";

import { SearchOrganizationByFullName, UpdateVerifyStatus } from "../_graphql/organizations";

const { Content } = Layout;

const OrganizationLayout = () => {
    const { graphqlFetchPlatform } = useModel("global");
    const { currentOrganizationFullName, currentOrganizationInfo, setCurrentOrganizationUuid, loadCurrentOrganizationBaseInfo } = useModel("organization.info");

    const state = useReactive({
        leftSiderWidth: 160,
        organizations: [],
        selectOptions: [],
    });

    const loadOrganizationInformation = async (keyword) => {
        let res = await graphqlFetchPlatform({
            query: SearchOrganizationByFullName,
            variables: { keyword },
        });
        return res?.a?.nodes || [];
    };

    const onSearch = async (inputValue) => {
        let value = inputValue.replace(/\s/g, "");
        if (value) {
            let res = await loadOrganizationInformation(value);
            if (res.length > 0) {
                state.selectOptions = res.map((item) => ({
                    uuid: item.uuid,
                    value: item.fullName,
                    label: item.fullName,
                }));
            }
        } else {
            state.selectOptions = [];
        }
    };

    const onSeletct = (info, option) => {
        setCurrentOrganizationUuid(option.uuid, option.value);
        state.selectOptions = [];
    };

    const HandleVerify = ({ record }) => {
        const confirm = async () => {
            state.submitLoading = true;
            if (record.usageStatus && record.initializationStatus) {
                let res = await graphqlFetchPlatform({
                    query: UpdateVerifyStatus,
                    variables: {
                        uuid: record.uuid,
                        verifyStatus: !record.verifyStatus,
                        verifyTime: !record.verifyStatus ? new Date().getUTCTime() : null,
                        updatedTime: new Date().getUTCTime(),
                    },
                });
                if (res) {
                    await loadCurrentOrganizationBaseInfo();
                }
            } else {
                message.warning("组织未启用或未初始化, 不能通过组织审核");
            }
            state.submitLoading = false;
        };

        return record.verifyStatus ? (
            <Popconfirm title="确认要暂停该组织的使用吗?" okButtonProps={{ loading: state.submitLoading }} onConfirm={confirm}>
                <Button size="small" type="primary" style={{ marginBottom: 4 }}>
                    已核准
                </Button>
            </Popconfirm>
        ) : (
            <Popconfirm title="确认要批准该组织的使用吗?" okButtonProps={{ loading: state.submitLoading }} onConfirm={confirm}>
                <Button size="small" type="danger" style={{ marginBottom: 4 }}>
                    待核准
                </Button>
            </Popconfirm>
        );
    };

    return (
        <Layout style={{ position: "fixed", left: 0, top: 93, width: state.leftSiderWidth, bottom: 0, right: 0 }}>
            <PageLeftMenu onChangeLeftSiderWidth={(newWidth) => (state.leftSiderWidth = newWidth)} />
            <Content
                id="main-body"
                style={{ backgroundColor: "var(--semi-color-fill-0)", position: "fixed", left: state.leftSiderWidth, top: 93, right: 0, bottom: 0 }}
            >
                <Nav mode="horizontal">
                    <Nav.Header text={currentOrganizationFullName || "-"}></Nav.Header>

                    <Nav.Footer>
                        <Space size={60}>
                            <Space size={20}>
                                <div>
                                    核准状态： <HandleVerify record={currentOrganizationInfo} />
                                </div>
                                <div>
                                    启用状态：
                                    <Button size="small" type={currentOrganizationInfo.usageStatus ? "primary" : "danger"} style={{ marginBottom: 4 }}>
                                        {currentOrganizationInfo.usageStatus ? "已启用" : "未启用"}
                                    </Button>
                                </div>
                                <div>
                                    初始化状态：{" "}
                                    <Button size="small" type={currentOrganizationInfo.initializationStatus ? "primary" : "danger"} style={{ marginBottom: 4 }}>
                                        {currentOrganizationInfo.initializationStatus ? "已初始化" : "未初始化"}
                                    </Button>
                                </div>

                                <div>
                                    当前部署模式：
                                    <Button
                                        size="small"
                                        type={currentOrganizationInfo.databaseDeployMode === "single" ? "primary" : "danger"}
                                        style={{ marginBottom: 4 }}
                                    >
                                        {currentOrganizationInfo.databaseDeployMode === "single" ? "单机部署模式" : "多机部署模式"}
                                    </Button>
                                </div>
                            </Space>
                            <AutoComplete
                                options={state.selectOptions}
                                prefix={<IconSearch />}
                                onSearch={onSearch}
                                onSelect={onSeletct}
                                filterOption={(inputValue, option) => option.value.indexOf(inputValue) !== -1}
                                style={{ width: 300 }}
                            >
                                <Input.Search placeholder="输入组织名称" enterButton />
                            </AutoComplete>
                        </Space>
                    </Nav.Footer>
                </Nav>
                <Outlet />
            </Content>
        </Layout>
    );
};

export default OrganizationLayout;
